package wk.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wk.dao.AdminMapper;
import wk.dao.AdminRolesMapper;
import wk.dao.LogMapper;
import wk.entity.Admin;
import wk.entity.AdminRoles;
import wk.entity.Log;
import wk.entity.Role;
import wk.service.AdminService;
import java.sql.SQLException;
import java.util.Date;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AdminRolesMapper adminRolesMapper;

    public Admin login(Admin admin) throws SQLException {
        Admin ad = adminMapper.findlogadmin(admin);
        if (ad != null) {
            Date date = new Date();
            ad.setLastLogTime(date);
            //更新用户登陆日期
            if (this.adminMapper.doUpdatebyLastDate(ad)) {
                //如果登陆成功，那么写入日志
                Log log = new Log();
                log.setAdmin(ad);
                log.setIp(ad.getIp());
                log.setLogTime(date);
                if (this.logMapper.doCreate(log)) {
                    return ad;
                }
            }
        }
        return null;
    }

    @Override
    public int getCountByadminname(String adminname) throws SQLException {
        return adminMapper.findbyadminname(adminname);
    }

    @Override
    public int insertadmin(Admin admin) throws SQLException {
        //在服务层也添加用户名是否重复的验证，如果重复了返回0
        if (getCountByadminname(admin.getAdminName()) != 1) {
            //设置默认属性，加入工作时间，头像，可用
            admin.setJobStartTime(new Date());
            admin.setPhoto("default.png");
            byte a = 1;
            admin.setActived(a);

            //初始化一个角色分配给当前注册的用户
            Role ro = new Role();
            ro.setId(1);

            //初始化一个角色和注册人的联系对象
            AdminRoles adminRoles = new AdminRoles();
            adminRoles.setAdmin(admin);
            adminRoles.setRole(ro);

            if (adminMapper.insertadmin(admin)==1){
                this.adminRolesMapper.doCreate(adminRoles);
                return 1;
            }
        }

        // 如果插入失败返回0
        return 0;
    }

    @Override
    public Boolean resetpassword(Admin admin) throws SQLException {
        return adminMapper.doUpdate(admin);
    }

    @Override
    public Admin find(Admin admin) throws SQLException {
        Admin result=null;
        result=adminMapper.find(admin);
        return result;
    }

}
